/**
 * @class Spark.DateField
 * @extends Spark.Component
 * <p>日期组件.
 * @author njq.niu@hand-china.com
 * @constructor
 * @param {Object} config 配置对象. 
 */
$S.DateField = Ext.extend($S.ViewComponent, {
	constructor: function(config) {
        $S.DateField.superclass.constructor.call(this,config);
    },
    initComponent : function(config){
        $S.DateField.superclass.initComponent.call(this, config);
        this.cellHeight = Math.round((this.height-36)/6);
        this.ct = this.ct||this.id;
        this.initTemplate();
        if(this.sbg) this.className += ' dbg'
        this.wrap = this.tpl.append(Ext.get(this.ct).dom,this,true);
        this.tbody = this.wrap.child("tbody");
        this.preBtn = this.wrap.child("div.s_df_pre");
        this.nextBtn = this.wrap.child("div.s_df_next");
        if(this.showPreBtn==false)this.preBtn.hide();
        if(this.showNextBtn==false)this.nextBtn.hide();
        this.textSpan = this.wrap.child("div.s_df_text");
        this.predraw(this.initDate || new Date());
    },
    initTemplate : function(){
        this.tpl = new Ext.Template(
            '<table class="{className}" style="width:{width}px;{style}" id="{id}" cellspacing="0">',
                '<thead>',
                    '<tr class="s_df_h">',
                        '<td colspan="7">',
                            '<div class="s_df_pre"></div>',
                            '<div class="s_df_next"></div>',
                            '<div class="s_df_text"></div>',
                        '</td>',
                    '</tr>',
                    '<tr class="s_df_w">',
                        '<td>日</td>',
                        '<td>一</td>',
                        '<td>二</td>',
                        '<td>三</td>',
                        '<td>四</td>',
                        '<td>五</td>',
                        '<td>六</td>',
                    '</tr>',
                '</thead>',
                '<tbody/>',
            '</table>');
    },
    processListener: function(ou){
    	$S.DateField.superclass.processListener.call(this,ou);
    	this.preBtn[ou]("click", this.preMonth, this);
        this.nextBtn[ou]("click", this.nextMonth, this);
    	this.wrap[ou]("click", this.onClick, this);
    	this.wrap[ou]('mousewheel',this.onMouseWheel,this);
    },
    initEvents : function(){
    	$S.DateField.superclass.initEvents.call(this);   	
    	this.addEvents(
    	/**
         * @event select
         * 选择事件.
         * @param {Spark.DateField} dateField 日期组件.
         * @param {Date} date 选择的日期.
         */
    	'select',
    	/**
         * @event unselect
         * 取消选择事件.
         * @param {Spark.DateField} dateField 日期组件.
         */
    	'unselect',
    	/**
         * @event render
         * 绘制事件.
         * @param {Spark.DateField} dateField 日期组件.
         */
    	'render',
    	/**
         * @event pre
         * 上一个月.
         * @param {Spark.DateField} dateField 日期组件.
         */
        'pre',
        /**
         * @event next
         * 下一个月.
         * @param {Spark.DateField} dateField 日期组件.
         */
        'next',
        /**
         * @event over
         * over事件.
         * @param {Spark.DateField} dateField 日期组件.
         * @param {Date} date 选择的日期.
         */
        'over');
    },
    destroy : function(){
    	delete this.overTd;
    	$S.DateField.superclass.destroy.call(this);
	},
	onMouseWheel : function(e){
        var delta = e.getWheelDelta();
        if(delta > 0){
            this.preMonth.defer(1,this);
        } else if(delta < 0){
            this.nextMonth.defer(1,this);
        }
        e.stopEvent();
    },
    onMouseOver: function(e){
        $S.DateField.superclass.onMouseOver.call(this,e);
    	var target = Ext.fly(e.target).findParent('td.s_day');
    	if(target && Ext.fly(target).getAttributeNS('','_date') != '0'){
    		this.focusDate(target);
    	}
    },
    onClick : function(e){
        var target = Ext.fly(e.target).findParent('td.s_day');
        this.selectTarget(target);
    },
    selectTarget: function(t){
        if(t) {
            var _d = Ext.fly(t).getAttributeNS('','_date');
        	if(_d != '0') this.select(new Date(parseInt(_d)));
    	}
    },
    focusDate : function(t){
        this.blurDate();
        this.overTd = t;
        Ext.fly(this.overTd).addClass('over');
        var d = new Date(parseInt(Ext.fly(t).getAttributeNS('','_date')));
        this.fireEvent('over', this, d);
    },
    blurDate : function(){
        if(this.overTd) {
            Ext.fly(this.overTd).removeClass('over');
            this.overTd = null;
        }
    },
    select : function(d){
    	if(!d)return;
    	if(this.sd) this.unselect(this.sd);
        if(d){
        	var cell = this.cache['_'+d.getTime()];
            if(cell && !Ext.fly(cell).hasClass('select'))Ext.fly(cell).addClass('select');
        }
        this.sd = d;
        this.fireEvent('select', this, this.sd);
    },
    unselect : function(d){
    	if(!d)return;
    	var cell = this.cache['_'+d.getTime()];
        if(cell){
            Ext.fly(cell).removeClass('select');
        }
        this.sd = null;
        this.fireEvent('unselect', this);
    },
	onSelectDay: function(o){
		if(!Ext.fly(o).hasClass('select'))Ext.fly(o).addClass('select');
	},
	onToday: function(o){
		Ext.fly(o).addClass("today");
	},
	/**
     * 上一月
     */
    preMonth: function(v,fire) {
        this.predraw(new Date(this.year, this.month - 2 - (v ? v - 1 : 0), 1));
        if(fire!=false)this.fireEvent('pre', this, v);
    },
    /**
     * 下一月
     */
    nextMonth: function(v,fire) {
        this.predraw(new Date(this.year, this.month+(v ? v - 1 : 0), 1));
        if(fire!=false)this.fireEvent('next', this, v);
    },
  	/**
  	 * 根据日期画日历
  	 * @param {Date} date 当前日期
  	 */
  	predraw: function(date) {
  		if(date=='' || !date.getFullYear) date = new Date();
  		this.date = date;
        this.year = date.getFullYear(); 
        this.month = date.getMonth() + 1;
        this.textSpan.update(date.format(this.format||"yyyy-mm"))
        this.draw();
        if(this.sbg) {
            this.wrap.removeClass(['dbg1','dbg2','dbg3','dbg4','dbg5','dbg6','dbg7','dbg8','dbg9','dbg10','dbg11','dbg12']);
            this.wrap.addClass('dbg'+this.month);
        }
        this.overTd = null;
        this.fireEvent('render', this);
  	},
	draw: function() {
		if(this.drawing) return;
		this.drawing = true;
		//用来保存日期列表
		this.cache = {};
        var arr = [];
        //用当月第一天在一周中的日期值作为当月离第一天的天数,用上个月的最后天数补齐
        for(var i = 1, firstDay = new Date(this.year, this.month - 1, 1).getDay(),lastDay = new Date(this.year, this.month - 1, 0).getDate(); i <= firstDay; i++){
            arr.push([n=lastDay-firstDay+i,new Date(this.year, this.month - 2, n),"s_day s_day_pre"]); 
        }
        //用当月最后一天在一个月中的日期值作为当月的天数
        for(var i = 1, monthDay = new Date(this.year, this.month, 0).getDate(); i <= monthDay; i++){ 
            arr.push([i,new Date(this.year, this.month - 1, i),"s_day"]); 
        }
        //用下个月的前几天补齐
        var l = 42 - arr.length;
        for(var i=1;i<=l;i++){
            arr.push([i,new Date(this.year, this.month, i),"s_day s_day_next"]); 
        }
        
        while(this.tbody.dom.firstChild){ 
          Ext.fly(this.tbody.dom.firstChild).remove();
        }
        
        var k=0;
        while(arr.length){
        	var row = document.createElement("TR");
            Ext.fly(row).set({'_r':k});
            row.style.height=this.cellHeight+"px";
            k++;
            for(var i = 1; i <= 7; i++){
                if(arr.length){
                    var d = arr.shift();
                    var cell = document.createElement("TD");
                    if(d &&d[1]){
                      var key = (''+d[1].getTime())
                      this.cache['_'+key]=cell;
                        cell.className = d[2];
                        cell.innerHTML = d[0];
                        this.renderCell(cell,d[1]);
                        var cf = Ext.fly(cell);
                        cf.set({'_c':i-1});
                        if(cell.disabled){
                            cf.set({'_date':'0'});
                            cf.addClass("s_day_disabled");
                        }else {
                            cf.set({'_date':key,'title':d[1].format('yyyy-mm-dd')});
                        }
                        if(d[2] == 's_day') {
                            if(new Date().isSame(d[1])) cell.className = cell.className + " today";
                            if(this.sd && d[1].isSame(this.sd)) this.onSelectDay(cell);
                        }
                    }
                    row.appendChild(cell);
                }
            }
            this.tbody.dom.appendChild(row);
        }
        this.drawing = false;
	},
	renderCell:function(cell,date){
		if(this.renderer)$S.getFunction(this.renderer).call(this,cell,date);
	}	
//	,isSame: function(d1, d2) {
//		if(!d2.getFullYear||!d1.getFullYear)return false;
//		return (d1.getFullYear() == d2.getFullYear() && d1.getMonth() == d2.getMonth() && d1.getDate() == d2.getDate());
//	}
});